const Controllers = require('../controllers/Controller.js').controller;
const formatTime_2 = require("../../utils/util").formatTime_2
const app = getApp();
Page({
  data: {
    globalStype: '',
    couponDetail: {},
    shopId: '',
    couponId: '',
    couponPushId: '',
    userId: '',
    fromUrl: '',
    shareBtn: false,
    giveBtn: false,
    receiveBtn: true,
    accountId: '',
    couponAccountId: '',
    backbool: true,
    isintelgral: false,
    isuserdetail: 0,
    sharereceivedata: '',
    shopInfo: {}, //店铺信息
    fufei: 0,
    isOnlyShow: false,
  },
  onLoad(option) {
    this.setData({
      globalStype: app.globalData.globalStype
    })
    console.log(option)
    if (option.invitationAccountId) {
      this.setData({
        invitationAccountId: option.invitationAccountId
      })
    }
    if (option.fufei) {
      this.setData({
        fufei: option.fufei
      })
    }
    if (option.isOnlyShow) {
      this.setData({
        isOnlyShow: true
      })
    }
    if (app.globalData.shopId) {
      this.setData({
        shopId: app.globalData.shopId
      })
    }
    if (option.shopId) {
      this.setData({
        shopId: option.shopId
      })
      app.globalData.shopId = option.shopId
      wx.setStorageSync('shopId', option.shopId)
    }
    if (option.id) {
      this.setData({
        couponId: option.id,
      })
    }
    if (option.accountId) {
      this.setData({
        accountId: option.accountId
      })
      // this.receiveGive(option.accountId, option.shopId, option.couponAccountId)
    }
    if (option.couponAccountId) {
      this.setData({
        couponAccountId: option.couponAccountId
      })
    }
    if (option.couponPushId) {
      this.setData({
        couponPushId: option.couponPushId
      })
    }

    if (getCurrentPages().length <= 1) {
      this.setData({
        backbool: false
      })
    } else {
      this.setData({
        backbool: true
      })
    }
    if (option.isintelgral) {
      this.setData({
        isintelgral: option.isintelgral
      })
    }
    if (option.isuserdetail) {
      this.setData({
        isuserdetail: option.isuserdetail
      })
    }
  },
  onShow() {
    //加载首页数据--
    // 无需登录，不可放入判断语句，重复进入不会有登录回调
    this.getDetails()
    if (wx.getStorageSync('usertoken')) {
      if (this.data.invitationAccountId) {
        this.invitationPerson()
      }
    } else {
      //无usertoken，等待login登录回调
      app.usertokenReadyCallback = res => {
        if (res.data.sessionId) {
          if (this.data.invitationAccountId) {
            this.invitationPerson()
          }
        }
      }
    }

  },

  // 拉新券领取
  pullNewReceive() {
    // 分享页进入携带accountId
    if (this.data.accountId) {
      // 分享页进入领取
      this.receiveGive()
    } else {
      // 领券中心进入领取
      this.receive()
    }
  },

  //领取优惠券
  receive(isShow = true) {
    if (!wx.getStorageSync('usertoken')) {
      app.GetLogin()
      return
    }
    let that = this;


    if (this.data.couponDetail.haveNum === 0 || (this.data.couponDetail.haveNum === 1 && this.data.couponDetail.num > 0)) {
      Controllers.receive({
        shopId: that.data.shopId,
        couponId: that.data.couponId,
        couponPushId: that.data.couponPushId
      }).then(res => {
        if (res.code == 1) {
          wx.navigateBack({
            delta: 1
          })
          wx.showToast({
            title: "领取成功",
            icon: 'none',
            duration: 800
          });
          that.getDetails()
        }
      })
    } else {
      wx.showToast({
        icon: "none",
        title: '该优惠券已领取完',
        duration: 1500
      })
    }

    // wx.requestSubscribeMessage({
    //   tmplIds:['CgSkX1UN123rlfAQ9zXiMyfiF1ugDkOsd8yLmvcbHt0','IoewIlKNaUfOLOhKUOdPKMOnJxdtdqWGfOotuOB2R70','TA4G0mjgPxvzTWGRTqvB9rkUfdot7EvAwJpRYfcLKcc'],//'TA4G0mjgPxvzTWGRTqvB9rkUfdot7EvAwJpRYfcLKcc'
    //   success:res=>{
    //     console.log(res)
    //   },
    //   complete:()=>{
    //     if(this.data.couponDetail.haveNum===0||(this.data.couponDetail.haveNum===1&&this.data.couponDetail.num>0)){
    //       Controllers.receive({shopId: that.data.shopId,couponId: that.data.couponId,couponPushId:that.data.couponPushId}).then(res=>{
    //         if(res.code==1){
    //           wx.navigateBack({
    //             delta: 1
    //           })
    //           wx.showToast({
    //             title: "领取成功",
    //             icon: 'none',
    //             duration: 800
    //           });
    //           that.getDetails()
    //         }
    //       })
    //     }else{
    //       wx.showToast({
    //         icon:"none",
    //         title: '该优惠券已领取完',
    //         duration:1500
    //       })
    //     }
    //   }
    // })
  },
  //获取详情
  getDetails() {
    let haveId = ""
    if (this.data.isuserdetail != 1) {

      if (this.data.accountId) {

        Controllers.accountShareDetails({
          shopId: this.data.shopId,
          couponAccountId: this.data.couponAccountId
        }).then(res => {
          if (res.code == 1) {
            if (res.data.type == 0) {
              res.data.typeText = '现金抵用'
            } else if (res.data.type == 1) {
              res.data.typeText = '满减'
            } else if (res.data.type == 2) {
              res.data.typeText = '限时限产品'
            } else if (res.data.type == 3) {
              res.data.typeText = '免费体验'
            } else if (res.data.type == 4) {
              res.data.typeText = '活动礼包'
            } else if (res.data.type == 5) {
              res.data.typeText = '拉新'
            }
            if (res.data.myCouponAccount) {
              res.data.stateText = '未使用'
            } else {
              if (res.data.couponAccount) {
                if (res.data.couponAccount.state == 0 || res.data.couponAccount.state == 3) {
                  res.data.stateText = '未领取'
                } else {
                  res.data.stateText = '已领取'
                }
              }
            }

            if (res.data.timeState == 1 && res.data.effectiveStartTime && res.data.effectiveEndTime) {
              res.data.effectiveStartTime = formatTime_2(res.data.effectiveStartTime.replace(/-/g, '/'))
              res.data.effectiveEndTime = formatTime_2(res.data.effectiveEndTime.replace(/-/g, '/'))
            }
            this.setData({
              couponDetail: res.data,
              couponPushId: res.data.couponPushId
            })
            this.myInformation();
            this.getShopInfo(); //获取店铺信息

          }
        })
      } else {

        if (this.data.couponAccountId) {
          haveId = this.data.couponAccountId
        }
        Controllers.details({
          shopId: this.data.shopId,
          couponId: this.data.couponId,
          couponAccountId: haveId
        }).then(res => {
          if (res.code == 1) {
            if (res.data.type == 0) {
              res.data.typeText = '现金抵用'
            } else if (res.data.type == 1) {
              res.data.typeText = '满减'
            } else if (res.data.type == 2) {
              res.data.typeText = '限时限产品'
            } else if (res.data.type == 3) {
              res.data.typeText = '免费体验'
            } else if (res.data.type == 4) {
              res.data.typeText = '活动礼包'
            } else if (res.data.type == 5) {
              res.data.typeText = '拉新'
            }
            if (res.data.couponAccount) {
              if (res.data.couponAccount.state == 0) {
                res.data.stateText = '未使用'
              } else if (res.data.couponAccount.state == 1) {
                res.data.stateText = '已使用'
              } else if (res.data.couponAccount.state == 2) {
                res.data.stateText = '已过期'
              } else if (res.data.couponAccount.state == 3 || !res.data.couponAccount) {
                res.data.stateText = '未领取'
              } else if (res.data.couponAccount.state == 4) {
                res.data.stateText = '已赠送'
              }
            } else {
              res.data.stateText = '未领取'
            }
            if (res.data.timeState == 1 && res.data.effectiveStartTime && res.data.effectiveEndTime) {
              res.data.effectiveStartTime = formatTime_2(res.data.effectiveStartTime.replace(/-/g, '/'))
              res.data.effectiveEndTime = formatTime_2(res.data.effectiveEndTime.replace(/-/g, '/'))
            }
            this.setData({
              couponDetail: res.data,
              couponPushId: res.data.couponPushId
            })
            this.myInformation()
            this.getShopInfo(); //获取店铺信息
            // 分享页进入不领取
            // if (res.data.type == 5) {
            //   this.sharereceive()
            // }
          }
        })
      }
    } else {

      Controllers.accountDetails({
        shopId: this.data.shopId,
        couponId: this.data.couponId,
        couponAccountId: this.data.couponAccountId
      }).then(res => {
        if (res.code == 1) {
          if (res.data.type == 0) {
            res.data.typeText = '现金抵用'
          } else if (res.data.type == 1) {
            res.data.typeText = '满减'
          } else if (res.data.type == 2) {
            res.data.typeText = '限时限产品'
          } else if (res.data.type == 3) {
            res.data.typeText = '免费体验'
          } else if (res.data.type == 4) {
            res.data.typeText = '活动礼包'
          } else if (res.data.type == 5) {
            res.data.typeText = '拉新'
          }
          if (res.data.couponAccount) {
            if (res.data.couponAccount.state == 0) {
              res.data.stateText = '未使用'
            } else if (res.data.couponAccount.state == 1) {
              res.data.stateText = '已使用'
            } else if (res.data.couponAccount.state == 2) {
              res.data.stateText = '已过期'
            } else if (res.data.couponAccount.state == 3 || !res.data.couponAccount) {
              res.data.stateText = '暂不可用'
            } else if (res.data.couponAccount.state == 4) {
              res.data.stateText = '已赠送'
            }
          }
          if (res.data.timeState == 1 && res.data.effectiveStartTime && res.data.effectiveEndTime) {
            res.data.effectiveStartTime = formatTime_2(res.data.effectiveStartTime.replace(/-/g, '/'))
            res.data.effectiveEndTime = formatTime_2(res.data.effectiveEndTime.replace(/-/g, '/'))
          }
          this.setData({
            couponDetail: res.data,
            couponPushId: res.data.couponPushId
          })
          this.myInformation()
          this.getShopInfo(); //获取店铺信息
        }
      })
    }
  },
  myInformation() {
    Controllers.myInformation({
      shopId: this.data.shopId
    }).then(res => {
      this.setData({
        userId: res.data.id
      })
    })
  },

  getShopInfo() {
    Controllers.shopDetails({
      shopId: this.data.shopId
    }).then(res => {
      this.setData({
        shopInfo: res.data
      })
    })
  },


  sharereceive() {
    Controllers.receive1({
      shopId: this.data.shopId,
      couponId: this.data.couponId,
      couponPushId: this.data.couponPushId
    }).then(res => {
      if (res.code == 1) {
        this.setData({
          sharereceivedata: res.data
        })
      }
    }).catch(res => {

    })
  },
  //分享或赠送
  onShareAppMessage: function (e) {
    if (!wx.getStorageSync('usertoken')) {
      app.GetLogin()
      return
    }
    // if(this.data.couponDetail.couponAccount){

    // }else{

    // }

    if (this.data.couponDetail.couponAccount) {

      // if(this.data.type!=4){
      let title = this.data.couponDetail.name;
      let imageUrl = '';
      let path = '/pages/Mall/Coupondetail?shopId=' + this.data.shopId + '&accountId=' + this.data.couponDetail.couponAccount.accountId + '&id=' + this.data.couponDetail.couponAccount.couponId + '&couponAccountId=' + this.data.couponDetail.couponAccount.id + "&invitationAccountId=" + this.data.userId
      console.log(path)
      let obj = {
        title,
        imageUrl,
        path,
        success: function (res) {

        },
        fail(err) {

        }
      }
      console.log(obj)
      return obj
      // }else{

      // }
    } else {

      let title = this.data.couponDetail.name;
      let imageUrl = '';
      let path = '/pages/Mall/Coupondetail?shopId=' + this.data.shopId + '&accountId=' + this.data.sharereceivedata.accountId + '&id=' + this.data.sharereceivedata.couponId + '&couponAccountId=' + this.data.sharereceivedata.id
      let obj = {
        title,
        imageUrl,
        path,
        success: function (res) {

        },
        fail(err) {

        }
      }
      console.log(obj)
    }

  },
  //领取赠送优惠券
  receiveGive() {
    if (!wx.getStorageSync('usertoken')) {
      app.GetLogin()
      return
    }

    let that = this;


    if (this.data.couponDetail.haveNum === 0 || (this.data.couponDetail.haveNum === 1 && this.data.couponDetail.num > 0)) {
      Controllers.receiveGive({
        accountId: that.data.accountId,
        shopId: that.data.shopId,
        couponAccountId: that.data.couponAccountId
      }).then(res => {
        if (res.code == 1) {
          wx.showToast({
            title: "领取成功",
            icon: 'none',
            duration: 800
          })
          that.getDetails()
        }
      })
    } else {
      wx.showToast({
        icon: "none",
        title: '该优惠券已领取完',
        duration: 1500
      })
    }

    // wx.requestSubscribeMessage({
    //   tmplIds:['CgSkX1UN123rlfAQ9zXiMyfiF1ugDkOsd8yLmvcbHt0','IoewIlKNaUfOLOhKUOdPKMOnJxdtdqWGfOotuOB2R70','TA4G0mjgPxvzTWGRTqvB9rkUfdot7EvAwJpRYfcLKcc'],//'TA4G0mjgPxvzTWGRTqvB9rkUfdot7EvAwJpRYfcLKcc'
    //   success:res=>{
    //     console.log(res)
    //   },
    //   complete:()=>{
    //     if(this.data.couponDetail.haveNum===0||(this.data.couponDetail.haveNum===1&&this.data.couponDetail.num>0)){
    //       Controllers.receiveGive({ accountId: that.data.accountId, shopId: that.data.shopId, couponAccountId: that.data.couponAccountId }).then(res => {
    //         if (res.code == 1) {
    //           wx.showToast({
    //             title: "领取成功",
    //             icon: 'none',
    //             duration: 800
    //           })
    //           that.getDetails()
    //         }
    //       })
    //     }else{
    //       wx.showToast({
    //         icon:"none",
    //         title: '该优惠券已领取完',
    //         duration:1500
    //       })
    //     }
    //   }
    // })


  },
  gouse() {
    if (this.data.couponDetail.goodsList && this.data.couponDetail.goodsList.length == 1) {
      wx.navigateTo({
        url: '/pages/Index/Detail?id=' + this.data.couponDetail.goodsList[0].id + "&shopId=" + this.data.couponDetail.shopId + '&couponAccountId=' + this.data.couponAccountId
      })
    } else {
      wx.navigateTo({
        url: '/pages/Mall/Mall?couponAccountId=' + this.data.couponAccountId,
      })
    }
  },
  gopage(e) {
    var url = e.currentTarget.dataset.url
    wx.navigateTo({
      url: url
    })
  },
  // backindex(e){
  //   console.log(e)
  //   let shopId=this.data.shopId
  //   console.log(shopId);
  //   if (wx.getStorageSync('usertoken')) {
  //       wx.navigateTo({
  //         url:'/pages/Index/Index?shopId='+shopId
  //       })
  //   }else{
  //     app.GetLogin();
  //   }
  // },

  backindex(e) {
    let page = getCurrentPages()
    let shopId = this.data.shopId
    console.log(page.length)
    if (page.length <= 1) {
      wx.redirectTo({
        url: '/pages/Index/Index?shopId=' + shopId,
      })
    }
  },

  //去活动券详情
  goToDetail() {
    let id = this.data.couponDetail.id;
    let couponPushId = this.data.couponDetail.couponPushId;
    wx.navigateTo({
      url: '/pages/Mall/Coupongiftbag?id=' + id + '&couponPushId=' + couponPushId,
    })
  },

  toMore() {
    wx.navigateTo({
      url: '/pages/Mall/Coupon',
    })
  },

  //绑定上级
  invitationPerson() {
    let value = {}
    value.invitationAccountId = this.data.invitationAccountId
    value.shopId = wx.getStorageSync('shopId')
    Controllers.invitationPerson(value).then(res => {

    })
  },
  // 去往店铺首页
  toStore() {
    wx.redirectTo({
      url: '/pages/Index/Index?shopId=' + this.data.shopId,
    })
  }




})